package com.itdong.securityconfig.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itdong.domain.User;
import com.itdong.securityconfig.dao.LoginUser;
import com.itdong.securityconfig.service.LoginService;
import com.itdong.utils.JwtUtils;
import com.itdong.utils.RedisUtils;
import com.itdong.utils.StringRedisUtils;
import com.itdong.vc.ResultVc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ResultVc userLogin(User user) {
        Authentication authentication_initial = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
        Authentication authentication_Filled = authenticationManager.authenticate(authentication_initial);

        authentication_Filled.getPrincipal();
        LoginUser loginUser = (LoginUser) authentication_Filled.getPrincipal(); //框架很烦人，给原loginUser对象加上了属性（username，password，和一个authorities
        Long userid_long = loginUser.getUser().getId();

        //生成token
        String userid = String.valueOf(userid_long);
        String token = JwtUtils.createToken(userid);
        Map<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("token", token);
        ResultVc resultVc = new ResultVc(stringStringHashMap, "登录成功");

        //将用户信息放进redis
        redisTemplate.opsForValue().set("login:"+userid, loginUser);
        //stringRedisTemplate.opsForValue().set("login:"+userid, loginUser.getUser().getEmail());

        return resultVc;
    }
}
